package com.aimer.service.impl;

import com.aimer.domain.User;
import com.aimer.domain.UserLogin;
import com.aimer.mapper.MenuMapper;
import com.aimer.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

// springboot会自动按条件装配的，如果判断出存在自定义实现UserDetailsService接口的类，就不会再注册自带的UserDetails
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 构造查询条件
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,username);

        // 在数据库中查询该用户
        User user = userMapper.selectOne(lambdaQueryWrapper);
        // 这里的密码校验给了springSecurity,你根据参数的用户名字查出来用户后
        // springSecurity会拿这个用户的信息和前端传参的值进行比较

        // 校验该用户是否存在
        if (Objects.isNull(user)){
            // 不存在抛出异常
            throw new  RuntimeException("该用户不存在");
        }

        // 根据用户查询权限信息封装到UserLogin
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        return new UserLogin(user,list);
    }
}
